﻿using System;
using System.IO;
using System.Xml.Linq;
using MaxStoreErp.Core.Interfaces;
using NLog;

namespace MaxStoreErp.Core.Infrastructure
{
    /// <summary>
    /// Базовая реализация логгера
    /// </summary>
    public class NLogLogger : ILogger
    {
        const string LoggerName = "MaxStoreErp";
        readonly Logger _logger;
        public NLogLogger()
        {
            if (!File.Exists("NLog.config"))
            {
                CreateDefaultConfiguration();
            }
            _logger = LogManager.GetLogger(LoggerName);
        }

        void CreateDefaultConfiguration()
        {
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
            var doc = new XDocument(new XElement("nlog",
                new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                new XElement("targets",
                    new XElement("target",
                        new XAttribute("name", "fileSpc"),
                        new XAttribute(xsi + "type", "AsyncWrapper"),
                        new XAttribute("queueLimit", "5000"),
                        new XAttribute("overflowAction", "Discard"),
                        new XElement("target",
                            new XAttribute(xsi + "type", "File"),
                            new XAttribute("fileName", "Logs/Store-${shortdate}.log"),
                            new XAttribute("layout", "${longdate} - ${level:uppercase=true}: ${message}"),
                            new XAttribute("createDirs", "true")))),
                new XElement("rules",
                    new XElement("logger",
                        new XAttribute("name", LoggerName),
                        new XAttribute("minlevel", "Debug"),
                        new XAttribute("writeTo", "fileSpc")))));
            doc.Save("NLog.config");
        }



        public void LogDebug(string message, params object[] parameters)
        {
            _logger.Debug(message, parameters);
        }

        public void LogInfo(string message, params object[] parameters)
        {
            _logger.Info(message, parameters);
        }

        public void LogWarning(string message, params object[] parameters)
        {
            _logger.Warn(message, parameters);
        }

        public void LogError(string message, params object[] parameters)
        {
            _logger.Error(message, parameters);
        }

        public void LogError(Exception exception, string message, params object[] parameters)
        {
            _logger.ErrorException(string.Format(message, parameters), exception);
        }

        public void LogError(Exception exception)
        {
            _logger.Error(exception);
        }
    }
}
